﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using GeneratorLib.DB;
using GeneratorLib.DB.Connectios;
using GeneratorLib.DB.Schemas;

namespace DBExplorer
{
    public partial class BatchGenerator : Form
    {
        public BatchGenerator()
        {
            InitializeComponent();
        }

        private IConnection _connectionInfo;
        public IConnection ConnectionInfo
        {
            get
            {
                return _connectionInfo;
            }
            set
            {
                _connectionInfo = value;
            }
        }

        private void BatchGenerator_Load(object sender, EventArgs e)
        {
            loadTables();
            loadTemplateFiles();
        }

        private void loadTables()
        {
            foreach (TableInfo table in this.ConnectionInfo.Tables)
            {
                var item= lsvTable.Items.Add(table.TableName);
                item.Checked = true;
                item.Tag = table;
            }
        }

        private void loadTemplateFiles()
        {
            string templateFileRoot = GlobalValues.CurrentPath + "/TemplateFiles";
            DirectoryInfo di = new DirectoryInfo(templateFileRoot);
            lsvTemplate.Items.Clear();
            addTemplateToMenu(di);
        }

        private void addTemplateToMenu(  DirectoryInfo direcory)
        {
            foreach (FileInfo fi in direcory.GetFiles("*.cmt"))
            {
                DBExplorer.TemplateGenerators.TemplateFile file = new TemplateGenerators.TemplateFile(fi.FullName);
                var item = lsvTemplate.Items.Add(file.TemplateName);
                item.SubItems.Add(file.FileName);
                item.Checked = true;
                item.Tag = file;
            }

            foreach (DirectoryInfo di in direcory.GetDirectories())
            {
                addTemplateToMenu( di);
            }

        }

        private void btALL1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lsvTable.Items.Count; i++)
            {
                lsvTable.Items[i].Checked = true;
            }
        }

        private void btUnAll1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lsvTable.Items.Count; i++)
            {
                lsvTable.Items[i].Checked = false;
            }

        }

        private void btAll2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lsvTemplate.Items.Count; i++)
            {
                lsvTemplate.Items[i].Checked = true;
            }
        }

        private void btUnAll2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lsvTemplate.Items.Count; i++)
            {
                lsvTemplate.Items[i].Checked = false;
            }
        }

        private void btGenerator_Click(object sender, EventArgs e)
        {
            List<TableInfo> tables = new List<TableInfo>();
            for (int i = 0; i < lsvTable.Items.Count; i++)
            {
                if (lsvTable.Items[i].Checked)
                    tables.Add((TableInfo)lsvTable.Items[i].Tag);
            }
            List<TemplateGenerators.TemplateFile> templates = new List<TemplateGenerators.TemplateFile>();
            for (int i = 0; i < lsvTemplate.Items.Count; i++)
            {
                if (lsvTemplate.Items[i].Checked)
                    templates.Add((TemplateGenerators.TemplateFile)lsvTemplate.Items[i].Tag);
            }

            if (tables.Count == 0 || templates.Count == 0) return;

            btGenerator.Enabled = false;
            progressBar1.Visible = true;
            progressBar1.Maximum = tables.Count * templates.Count;
            progressBar1.Minimum = 0;
            progressBar1.Value = 0;

            foreach (TableInfo table in tables)
            {
                foreach (TemplateGenerators.TemplateFile template in templates)
                {
                    generator(table, template);
                    progressBar1.Value  ++;
                }
            }
            progressBar1.Visible = false;
            btGenerator.Enabled = true;

            MessageBox.Show("Generator Finished!");
            //this.DialogResult = DialogResult.OK;
            //this.Close();
        }

        private void generator(TableInfo table, TemplateGenerators.TemplateFile template)
        {
            TemplateGenerators.TemplateToCode templateToCode = null;

            string templateSource = string.Empty;
            using (StreamReader sr = new StreamReader(template.FileName))
            {
                templateSource = sr.ReadToEnd();
            }

            templateToCode = new TemplateGenerators.TemplateToCode(table, templateSource);
            string saveTo = Path.Combine(templateToCode.OutputConfig.GetAutoSavePath(), templateToCode.OutputConfig.GetAutoSaveFileName());
            if (File.Exists(saveTo))
            {
                int i = 1;
                FileInfo fi = new FileInfo(saveTo);

                string f1, f2, f3;
                f1 = fi.Directory.FullName;
                f2 = fi.Name.Replace(fi.Extension, "");
                f3 = fi.Extension;
                while (true)
                {

                    if (!File.Exists(Path.Combine(f1, string.Format("{0}({2}){1}", f2, f3, i))))
                    {
                        saveTo = Path.Combine(f1, string.Format("{0}({2}){1}", f2, f3, i));
                        break;
                    }
                }
            }
            else
            {
                FileInfo fi = new FileInfo(saveTo);
                if (!Directory.Exists(fi.Directory.FullName))
                {
                    Directory.CreateDirectory(fi.Directory.FullName);
                }

            }

            if (templateToCode == null) return;

            File.Create(saveTo).Close();
            string msg = "syntax error! Check File please!";
            if (templateToCode.CheckSyntax() == false)
            {
                using (StreamWriter sw = new StreamWriter(saveTo))
                {
                    sw.WriteLine(msg);
                }
            }
            else
            {
                templateToCode.ConvertToCSharp();

                using (StreamWriter sw = new StreamWriter(saveTo))
                {
                    sw.Write(templateToCode.ResultCode);
                }               
            }

        }

        private void BatchGenerator_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = progressBar1.Visible;
        }




    }
}
